import os
import filecmp
import shutil
import subprocess
import tempfile
import stat
import pwd
import grp
import time
import os.path

class ConfigureRepositories:
    def __init__(self, repositories):
        self.repos = repositories
        self.successful = 0
        self.failed     = 0
        self.oo_sync    = 0

    def configure(self):
        """
        Configure repository resources.
        """
        print "\033[1;36m- Configuring Repositories\033[1;m"
        runtime_start = time.time()

        for repo in self.repos:
            had_to_refresh = False
            old_file = self.repos[repo]['path']

            # Setup and write incoming file content to tempfile.
            t = tempfile.NamedTemporaryFile()
            t.write(self.repos[repo]['content'])
            t.flush()

            new_file = t.name
            # Check if the file resource exist on the client
            if os.path.isfile(old_file):
                # Compare exsiting file and incoming changes
                if filecmp.cmp(old_file, new_file):
                    self.successful += 1
                else:
                    # Show diff and overwrite exsiting file with temp
                    self.diff_files(old_file, new_file)
                    shutil.copy(new_file, old_file)
                    subprocess.call(['chmod', '0644', old_file])
                    had_to_refresh = True
            else:
                print "%s not found, creating..." % (old_file)
                subprocess.call(['touch', old_file])
                shutil.copy(new_file, old_file)
                subprocess.call(['chmod', '0644', old_file])
                had_to_refresh = True
            # Close temporary file.
            t.close()

            if had_to_refresh:
                self.oo_sync += 1

        # Collect Stats
        runtime_end = time.time()
        runtime = (runtime_end - runtime_start)

        stats = {
            'runtime'   : runtime,
            'successful': self.successful,
            'failed'    : self.failed,
            'oo_sync'   : self.oo_sync
        }

        return stats

    def diff_files(self, file1, file2):
        """
        Diff two files by shelling out to local system diff command.
        Make this configurable?
        """
        subprocess.call(['/usr/bin/diff', file1, file2])
